const db = require('../../database')
const getToken = require('../router_handlers/getToken')
const writeLogs = require('./writeLogs');

module.exports = (req, res) => {
    const {oldName, newName} = req.body;
    if (oldName !== req.auth.username) return res.cc('用户身份验证信息不匹配')

    const sql = 'update users set username = ? where username = ?';
    db.query(sql, [newName, oldName], (err, data) => {
        if (err) {
            if (err.code === 'ER_DUP_ENTRY') return res.cc('该用户名已存在')
            return res.cc(err)
        }
        if (data.affectedRows === 0) return res.cc('原用户名不存在')
        writeLogs('edit', {
            username: oldName,
            info: '用户名',
            newInfo: newName,
        })
        res.cc(getToken(newName), 0);
    })
}